/*
 * @Author: hrc 
 * @Date: 2024-10-09 14:16:43
 * @LastEditors: HuRrongChao
 * @LastEditTime: 2025-04-18 17:48:22
 */
// 配置拦截器
import axios from 'axios'
import store from './store'
import api from '@/api/axios.js'
import { ElMessage } from 'element-plus'

// 配置全局的 axios 默认值
axios.defaults.baseURL = '/api'
// 请求头设置token：AUTH_TOKEN
// axios.defaults.headers.common['Authorization'] = '1111111';
// 添加请求拦截器
axios.interceptors.request.use(function (config) {
  // 在发送请求之前做些什么
  config.params = {
    ...config.params,  //es6解构赋值，把前面传过来的params放在这，然后拼接下面的数据，作用是为了防止再次传数据时把params给覆盖了
    user_id: store.state.user.user_id,
    school_code: store.state.user.school_code,
    time: new Date().getTime()
  }
  config.headers.authorization = store.state.user.token
  return config
}, function (error) {
  // 对请求错误做些什么
  return Promise.reject(error)
})

// 防抖，防止频繁请求token
let timer = null
// 添加响应拦截器
axios.interceptors.response.use(function (response) {
  // 对响应数据做点什么
  if (response.data.code === 0 && response.data.type === 'lapse_token') {
    if (timer) clearTimeout(timer)
    timer = setTimeout(() => {
      api.getRefreshToken({
        token: store.state.user.token
      }).then((refreshToken) => {
        console.log('refreshToken', refreshToken)
        const refreshTokenData = refreshToken.data
        if (refreshTokenData.code === '200' && refreshTokenData.msg === 'success') {
          store.commit('user/SET_REFRESH_TOKEN', refreshTokenData.token)
          store.state.user.token = refreshTokenData.token
          store.state.user.isLogin = true
        } else if (refreshTokenData.code === 0 && refreshTokenData.type === 'loginAgain') {
          store.state.user.isLogin = false
          ElMessage({
            message: '请先登录!',
            type: 'warning'
          })
        }
      }).catch((err) => {
        console.log('err', err)
      })
    }, 500)
  }
  return response;
}, function (error) {
  // 对响应错误做点什么
  return Promise.reject(error);
});

export default axios